package cn.huaqingcheng.tianshu.core.uc.service;

import cn.huaqingcheng.tianshu.core.uc.model.AccountKeyValue;
import cn.huaqingcheng.tianshu.core.uc.model.AccountSettingKey;
import cn.huaqingcheng.tianshu.core.uc.model.BackgroundSetting;
import cn.huaqingcheng.tianshu.core.uc.model.GeneralSetting;
import cn.huaqingcheng.tianshu.core.uc.repository.AccountKeyValueRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * AccountSettingServiceImpl
 */
@Service
@RequiredArgsConstructor
public class AccountSettingServiceImpl implements AccountSettingService {

    private final AccountKeyValueRepository keyValueRepository;


    @Override
    @Transactional(readOnly = true)
    public BackgroundSetting getBackgroundSetting(Long accountId) {
        return keyValueRepository.selectByKey(AccountSettingKey.背景设置, accountId)
                .map(kv -> BackgroundSetting.of(kv.getValue()))
                .orElseGet(BackgroundSetting::newDefault);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BackgroundSetting setBackgroundSetting(Long accountId, BackgroundSetting setting) {
        AccountKeyValue keyValue = new AccountKeyValue()
                .setAccountId(accountId)
                .setKey(AccountSettingKey.背景设置)
                .setValue(setting.toMap());

        Optional<AccountKeyValue> optional = keyValueRepository.selectByKey(AccountSettingKey.背景设置, accountId);
        if (optional.isEmpty()) {
            AccountKeyValue save = keyValueRepository.save(keyValue);
            return BackgroundSetting.of(save.getValue());
        }

        AccountKeyValue value = keyValueRepository.updateByKey(keyValue, AccountSettingKey.背景设置);
        return BackgroundSetting.of(value.getValue());
    }

    @Override
    @Transactional(readOnly = true)
    public GeneralSetting getGeneralSetting(Long accountId) {
        return keyValueRepository.selectByKey(AccountSettingKey.常规设置, accountId)
                .map(kv -> GeneralSetting.of(kv.getValue()))
                .orElseGet(GeneralSetting::newDefault);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public GeneralSetting setGeneralSetting(Long accountId, GeneralSetting setting) {
        AccountKeyValue keyValue = new AccountKeyValue()
                .setAccountId(accountId)
                .setKey(AccountSettingKey.常规设置)
                .setValue(setting.toMap());

        Optional<AccountKeyValue> optional = keyValueRepository.selectByKey(AccountSettingKey.常规设置, accountId);
        if (optional.isEmpty()) {
            AccountKeyValue save = keyValueRepository.save(keyValue);
            return GeneralSetting.of(save.getValue());
        }
        AccountKeyValue value = keyValueRepository.updateByKey(keyValue, AccountSettingKey.常规设置);
        return GeneralSetting.of(value.getValue());
    }

}
